package ejb;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.VoteDTO;
import model.Citizen;
import model.Member;
import model.Party;
import model.Vote;
import entitymanagers.VoteManager;
import utils.AbstractBean;

@Stateless
@LocalBean
public class VoteManagerBean extends AbstractBean<Vote> implements VoteManager{

	public VoteManagerBean() {
		super(Vote.class);
	
	}
	@PersistenceContext
	private EntityManager em;
	@Resource
	private SessionContext context;
	
	@Override
	public void addVote(VoteDTO vote) {
		Citizen c = em.find(Citizen.class, context.getCallerPrincipal().getName());
		Party p = em.find(Party.class, vote.getParty().getIdParty());
		int max = 3;
		Member[] pref = new Member[max]; //preferences array
		
		pref[0] = em.find(Member.class, vote.getPreference1().getIdMember());
		pref[1] = em.find(Member.class, vote.getPreference2().getIdMember());
		pref[2] = em.find(Member.class, vote.getPreference3().getIdMember());
		
		Vote newVote = new Vote (c, p, pref);
		create(newVote);
		
		p.addVote(newVote);
		em.merge(p);
		c.setVote(newVote);
		em.merge(c);
		
		switch(max){
		case 1: 	pref[0].addVote(newVote);
					em.merge(pref[0]);
		case 2: 	pref[0].addVote(newVote);
					em.merge(pref[0]);
					pref[1].addVote(newVote);
					em.merge(pref[1]);
					break;
		case 3:
					pref[0].addVote(newVote);
					em.merge(pref[0]);
					pref[1].addVote(newVote);
					em.merge(pref[1]);
					pref[2].addVote(newVote);
					em.merge(pref[2]);
					break;
		default: break;
		}
		em.flush();
		
	}



	

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

}
